<template>
    <div class="admin-page">
        <div class="page-header">
            <div style="display: flex;">
                <div style="display: flex; flex-wrap: wrap; align-items: center; gap: 15px; margin-bottom: 15px;">
                    <div style="display: flex; align-items: center;" class="search-item">
                        <span class="search-label">号码:</span>
                        <el-input v-model="form.search" size="small" placeholder="订单号/手机号"
                                  style="width: 160px;"></el-input>
                    </div>
                    <div style="display: flex; align-items: center;" class="search-item">
                        <span class="search-label">渠道用户:</span>
                        <el-select v-model="form.channel_id" size="small" style="width: 110px;" placeholder="全部" clearable>
                            <el-option v-for="(item, index) in qudaoList" :key="index" :label="item.name" :value="item.id"></el-option>
                        </el-select>
                    </div>
                    <div style="display: flex; align-items: center;" class="search-item">
                        <span class="search-label">订单分类:</span>
                        <el-select v-model="form.type" size="small" style="width: 130px;" placeholder="全部">
                            <el-option label="全部" value=""></el-option>
                            <el-option label="普通订单" value="1"></el-option>
                            <el-option label="服务商订单" value="2"></el-option>
                        </el-select>
                    </div>
                    <div style="display: flex; align-items: center;" class="search-item">
                        <span class="search-label">订单状态:</span>
                        <el-select v-model="form.state" size="small" style="width: 120px;" placeholder="全部">
                            <el-option label="全部" value=""></el-option>
                            <el-option label="未支付" value="0"></el-option>
                            <el-option label="已支付" value="1"></el-option>
                            <el-option label="已发货" value="2"></el-option>
                            <el-option label="已完成" value="3"></el-option>
                            <el-option label="已退款" value="4"></el-option>
                        </el-select>
                    </div>
                    <div style="display: flex; align-items: center;" class="search-item">
                        <span class="search-label">日期:</span>
                        <el-date-picker
                            size="small"
                            v-model="form.start_time"
                            type="date"
                            style="width: 150px;"
                            placeholder="开始日期">
                        </el-date-picker>
                        <span style="margin: 0 5px;">至</span>
                        <el-date-picker
                            size="small"
                            style="width: 150px;"
                            v-model="form.end_time"
                            type="date"
                            placeholder="结束日期">
                        </el-date-picker>
                    </div>

                    <div style="display: flex; align-items: center;" class="search-item">
                        <span class="search-label">总业绩:</span>
                        <span class="red-input-no-border">{{ form.total_price }}</span>
                    </div>

                </div>
                <div style="display: flex;  align-items: center; gap: 15px; margin-bottom: 15px;">
                    <el-button type="primary" size="small" @click="toSearch">搜索</el-button>
                    <el-button type="success" size="small" @click="reset">重置</el-button>
                    <el-button size="small" @click="exportToExcel">导出</el-button>
                    <el-button size="small" @click="ToDaoChu">导入</el-button>
                </div>
            </div>
        </div>
        <el-table height="560" :data="adminList" border style="width: 100%;overflow-y: auto"
                  :header-cell-style="{background:'#FAFAFA',color:'#666', fontSize:'13px'}" size="small"
                  :row-class-name="tableRowClassName"
                  @row-click="onQuadClick">
            <el-table-column prop="id" label="ID" align="center" width="80"/>
            <el-table-column prop="uuid" label="用户ID" align="center" width="80"/>
            <el-table-column prop="nickname" align="center" label="用户名" width='150'/>
            <el-table-column prop="username" align="center" label="手机号" width='150'/>
            <el-table-column prop="ordernum" align="center" label="订单号" width='150'/>
            <el-table-column prop="total_num" align="center" label="总数量" width="60"/>
            <el-table-column prop="total_price" align="center" label="总价格" width="80"/>
            <el-table-column prop="type" align="center" label="类型" width="100">
                <template slot-scope="scope">
                    {{ scope.row.type === 1 ? "普通订单" : '服务商订单' }}
                </template>
            </el-table-column>
            <el-table-column label="下单时间" align="center" width="160">
                <template slot-scope="scope">
                    {{ formatTimestamp(scope.row.pay_time) }}
                </template>
            </el-table-column>
            <el-table-column align="center" prop="fh_time" label="发货时间"  width="160">
                <template slot-scope="scope">
                    {{ scope.row.fh_time !== 0 ? formatTimestamp(scope.row.fh_time) : '-' }}
                </template>
            </el-table-column>
            <el-table-column prop="state" align="center" label="订单状态" width="80"/>
            <el-table-column prop="fahuo" align="center" label="发货状态" width="80"/>
            <!--            <el-table-column align="center" prop="state" label="订单状态" width="80">
                            <template slot-scope="scope">
                                {{ getLevelName(scope.row.state) }}
                            </template>
                        </el-table-column>
                        <el-table-column align="center" prop="fahuo" label="发货状态" width="80">
                            <template slot-scope="scope">
                                {{ getLevelName(scope.row.fahuo) }}
                            </template>
                        </el-table-column>-->
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button type="text" size="mini" @click="handleEdit(scope.row)">订单详情
                    </el-button>
                    <el-button type="text" size="mini" @click="toFen(scope.row)">分红
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                       :current-page="currentPage" :page-size="pageSize"
                       layout="total,  pager, next" :total="total"/>
        <el-dialog
            title="订单详情"
            :visible.sync="editDialogVisible"
            width="700px"
            :close-on-click-modal="false"
        >
            <el-form
                :model="adminForm"
                ref="adminForm"
                label-width="100px"
                size="small"
            >
                <el-form-item label="订单号" prop="ordernum">
                    <el-input style="width: 90%;" v-model="adminForm.ordernum" disabled/>
                </el-form-item>
                <el-form-item label="用户名" prop="name">
                    <el-input style="width: 90%;" v-model="adminForm.name"/>
                </el-form-item>
                <el-form-item label="收货人电话" prop="tel">
                    <el-input style="width: 90%;" v-model="adminForm.tel"/>
                </el-form-item>
                <el-form-item label="省市区">
                    <el-input
                        style="width: 30%;"
                        v-model="adminForm.province"
                        placeholder="请输入省份"
                    />
                    <el-input
                        style="width: 30%;"
                        v-model="adminForm.city"
                        placeholder="请输入城市"
                    />
                    <el-input
                        style="width: 30%;"
                        v-model="adminForm.district"
                        placeholder="请输入区县"
                    />
                </el-form-item>
                <el-form-item label="地址">
                    <el-input
                        type="textarea"
                        :rows="10"
                        style="width: 90%;"
                        v-model="adminForm.address"
                    />
                </el-form-item>
                <el-form-item label="快递公司" prop="express">
                    <el-select
                        :clearable="true"
                        v-model="adminForm.express"
                        placeholder="请选择快递公司"
                        filterable
                    >
                        <el-option
                            v-for="item in newArr"
                            :key="item.key"
                            :label="item.value"
                            :value="item.key">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="运单号" prop="express_code">
                    <el-input style="width: 90%;" v-model="adminForm.express_code"/>
                </el-form-item>

                <el-form-item label="备注" prop="remark">
                    <el-input style="width: 90%;" type="textarea" :row="2" v-model="adminForm.remark"/>
                </el-form-item>

                <el-form-item label="确认发货" prop="state">
                    <el-radio-group v-model="adminForm.state">
                        <el-radio :label="1">不发货</el-radio>
                        <el-radio :label="2">发货</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="商品列表">
                    <el-table :data="orderList">
                        <el-table-column prop="title" label="商品名称"/>
                        <el-table-column prop="f_thumb" label="产品封面" width="80">
                            <template slot-scope="scope">
                                <img style="width: 50px;height: 50px"
                                     :src="$appConfig.imgPath + scope.row.f_thumb"/>
                            </template>
                        </el-table-column>
                        <el-table-column prop="num" label="商品数量"/>
                        <el-table-column prop="price" label="商品价格"/>
                        <el-table-column prop="total_price" label="商品总价格"/>
                    </el-table>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false" size="small">取消</el-button>
                <el-button type="primary" @click="submitForm" size="small">确定</el-button>
            </div>
        </el-dialog>


        <el-dialog
            title="订单导入"
            :visible.sync="showDaoChuDialog"
            width="90%"
            :close-on-click-modal="false"
        >
            <div v-if="!uploadSuccess">
                <el-form
                    :model="adminForm"
                    ref="adminForm"
                    label-width="100px"
                    size="small"
                >
                    <el-form-item label="上传Excel">
                        <el-upload
                            class="excel-uploader"
                            action="/admin/shop/imgUpload"
                            :headers="{ token: userInfo.token }"
                            :data="{ type: 1 }"
                            :show-file-list="false"
                            :on-success="handleUploadSuccess"
                            :on-error="handleUploadError"
                            :before-upload="beforeExcelUpload"
                            :file-list="fileList"
                        >
                            <div v-if="!adminForm.excelFileUrl" class="uploader-box">
                                <i class="el-icon-upload el-icon--right"></i>
                                <span>点击上传Excel文件</span>
                            </div>
                            <div v-else class="uploaded-file">
                                <i class="el-icon-document"></i>
                                <span>{{ adminForm.excelFileName }}</span>
                                <el-button
                                    size="mini"
                                    type="text"
                                    @click="removeFile"
                                >
                                    移除
                                </el-button>
                            </div>
                        </el-upload>
                        <div class="upload-tip">
                            <i class="el-icon-info"></i>
                            <span>仅支持上传.xlsx或.xls格式的Excel文件</span>
                        </div>
                    </el-form-item>
                </el-form>
            </div>

            <div v-else class="import-result">
                <div class="stats-card">
                    <div class="stat-item">
                        <div class="stat-title">成功订单数量</div>
                        <div class="stat-value">{{ successCount }}</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-title">失败订单数量</div>
                        <div class="stat-value error">{{ failCount }}</div>
                    </div>
                </div>

                <el-table height="560" v-if="orderForm.length < 300" :data="orderForm" border style="width: 100%;overflow-y: auto"
                          :header-cell-style="{background:'#FAFAFA',color:'#666', fontSize:'13px'}" size="small">
                    <el-table-column prop="express" label="快递公司" align="center" width="80">
                        <template slot-scope="scope">
                            {{ getExpressName(scope.row.express) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="express_code" label="运单号" align="center"/>
                    <el-table-column prop="ordernum" align="center" label="订单号"/>
                    <el-table-column prop="message" align="center" label="错误信息"/>
                </el-table>
                <div v-else>
                    数据过多,请导出
                </div>
            </div>

            <div class="dialog-footer">
                <el-button @click="closeDialog" size="small">取消</el-button>
                <el-button
                    v-if="!uploadSuccess"
                    type="primary"
                    @click="submitForm1"
                    size="small"
                    :disabled="!adminForm.excelFileUrl"
                >
                    确定
                </el-button>
                <el-button
                    v-if="orderForm.length >= 300"
                    type="primary"
                    @click="saveOrder"
                    size="small"
                >
                    导出
                </el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {mapState} from "vuex";

export default {
    data() {
        return {
            qudaoList:[],
            levelMap: [
                "未支付",
                "已支付",
                "已发货",
                "已完成",
                "已退款",
            ],
            adminList: [],
            orderList: [],
            currentPage: 1,
            pageSize: 15,
            total: 0,
            form: {
                search: "",
                type: "",
                pay_type: "",
                total_price: "",
                state: "",
                fahuo: "",
                channel_id: "",
                start_time: "",
                end_time: ""
            },
            addDialogVisible: false,
            editDialogVisible: false,
            showDaoChuDialog: false,
            adminForm: {
                id: 0,
                express_code: "",
                remark: "",
                state: 1,
                fahuo: 0,
                express: 1,
                type: 1,
                province: "",
                tel: "",
                name: "",
                city: "",
                district: "",
                address: "",
                excelFileUrl: '',
                excelFileName: '',
                thumb: ''
            },
            fileList: [],
            uploadSuccess: false,
            successCount: 0,
            failCount: 0,
            exportCount: 0,
            orderForm: {
                express_code: "",
                ordernum: "",
                message: "",
            },
            rules: {
                express_code: [
                    { required: true, message: '请填写运单号', trigger: 'blur' }
                ]
            },
            statusList: [
                {
                    id: 1,
                    name: "显示"
                },
                {
                    id: 0,
                    name: '隐藏'
                }
            ],
            imageUrl: '',
            imageUrl1: '',
            searchParams: {},
            newArr: [],
            highlightOrderIds: [],
        };
    },
    computed:{
        ...mapState(["userInfo"]),
        getExpressName() {
            return (express) => {
                const item = this.newArr.find((obj) => obj.key === express);
                return item? item.value : '';
            };
        }
    },
    mounted() {
        this.fetchAdminList();
        this.fetchAdminList1();
        this.getKuaidi();
        this.changeBgc()
    },
    methods: {
        fetchAdminList1() {
            const params = {
                type: 3,
                page: this.currentPage,
                limit: this.pageSize
            };
            this.$http.get('/admin/single/lists', {params}).then(result => {
                console.log(result)
                const newArr = []
                if(result.code === 200){
                    result.data.data.forEach(item=>{
                        newArr.push({name:item.name,id:item.id})
                    })
                    console.log(newArr)
                    this.qudaoList = newArr
                }
            });
        },
        beforeExcelUpload(file) {
            const isExcel = file.type === 'application/vnd.ms-excel' ||
                file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
            const isLt20M = file.size / 1024 / 1024 < 20;

            if (!isExcel) {
                this.$message.error('请上传Excel文件!');
            }
            if (!isLt20M) {
                this.$message.error('文件大小超过20MB!');
            }

            this.adminForm.excelFileName = file.name;
            return isExcel && isLt20M;
        },

        // 处理上传成功
        handleUploadSuccess(response, file, fileList) {
            if (response.code === 200) {
                this.adminForm.excelFileUrl = response.data[0];
                this.$message.success('文件上传成功');
                // 模拟获取订单数据
                // this.fetchOrderData();
            } else {
                this.$message.error(response.message || '上传失败');
            }
        },

        // 处理上传失败
        handleUploadError(err, file, fileList) {
            this.$message.error('上传失败，请重试');
        },

        // 移除已上传文件
        removeFile() {
            this.adminForm.excelFileUrl = '';
            this.adminForm.excelFileName = '';
            this.fileList = [];
        },

        // 提交表单
        submitForm1() {
            if (!this.adminForm.excelFileUrl) {
                this.$message.warning('请先上传Excel文件');
                return;
            }

            // 调用导入接口
            this.$http.post('/admin/OrderImport/orderDataimport', {
                path: this.adminForm.excelFileUrl,
            }).then(result => {
                if (result.code === 200) {
                    this.uploadSuccess = true;
                    this.successCount = result.data.success_num || 0;
                    this.failCount = result.data.error.length || 0;
                    this.exportCount = result.data.exportCount || 0;

                    // 填充订单表单数据
                    this.orderForm = result.data.error;
                    console.log(this.orderForm)

                } else {
                    this.$message.error(result.message || '导入失败');
                }
            }).catch(error => {
                this.$message.error('网络错误，请重试');
            });
        },

        // 填充订单表单数据
        // 保存订单
        saveOrder() {
            // 调用保存订单接口
            this.$http.post('/admin/Order/save', this.orderForm)
                .then(result => {
                    if (result.code === 200) {
                        this.$message.success('订单保存成功');
                        this.closeDialog();
                    } else {
                        this.$message.error(result.message || '保存失败');
                    }
                })
                .catch(error => {
                    this.$message.error('网络错误，请重试');
                });
        },

        // 关闭对话框
        closeDialog() {
            this.showDaoChuDialog = false;
            this.resetForm();
        },

        // 重置表单
        resetForm() {
            this.adminForm = {
                excelFileUrl: '',
                excelFileName: '',
                thumb: ''
            };
            this.fileList = [];
            this.uploadSuccess = false;
            this.successCount = 0;
            this.failCount = 0;
            this.exportCount = 0;
            this.orderForm = {};
        },
        getKuaidi() {
            this.$http.get('/admin/Order/getOrderExcepressType').then(result => {
                // 假设result.data就是你获取到的原始对象数据
                const originalData = result.data;
                const newData = Object.entries(originalData).map(([key, value]) => ({
                    key: Number(key),
                    value: value
                }));
                // 这里newData就是转换后的数组对象格式
                // 如果你想在Vue实例中使用，可以将其赋值给一个data中的属性
                this.newArr = newData;
                console.log(this.newArr)
            });
        },
        toFen(row) {
            this.$router.push({path: 'dividend', query: {data: row}})
        },
        formatTimestamp(timestamp) {
            if (!timestamp) return '-';
            // 处理毫秒级时间戳（如果是秒级需*1000）
            const date = new Date(timestamp * 1000);
            // 提取时间组件
            const year = date.getFullYear();
            const month = (date.getMonth() + 1).toString().padStart(2, '0');
            const day = date.getDate().toString().padStart(2, '0');
            const hours = date.getHours().toString().padStart(2, '0');
            const minutes = date.getMinutes().toString().padStart(2, '0');
            const seconds = date.getSeconds().toString().padStart(2, '0');

            // 拼接成目标格式
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        getLevelName(value) {
            const index = parseInt(value);
            return this.levelMap[index];
        },

        fetchAdminList(params = {}) {
            const mergedParams = {
                ...params,  // 先展开传入的参数
                page: params.page || this.currentPage,  // 优先使用传入的页码
                limit: 15  // 固定每页显示数量
            };
            this.$http.get('/admin/Order/lists', {params: mergedParams}).then(result => {
                if (result.code === 200) {
                    this.form.total_price = result.data.total_price
                    this.adminList = Array.isArray(result.data.data) ? result.data.data : [];
                    this.total = parseInt(result.data.total) || 0;
                } else {
                    this.$message.error(result.msg);
                    this.adminList = [];
                    this.total = 0;
                }
            }).catch(error => {
                this.$message.error("获取订单列表失败，请稍后重试");
                this.adminList = [];
                this.total = 0;
            });
        },
        handleSizeChange(val) {
            this.pageSize = val;
            this.currentPage = 1;
            this.fetchAdminList(this.searchParams);
        },
        handleCurrentChange(val) {
            this.currentPage = val;
            this.fetchAdminList(this.searchParams);
        },
        handleEdit(row) {
            this.adminForm.id = row.id
            // 调用接口获取详细数据
            this.$http.get(`/admin/Order/orderDetail`, {params: {id: row.id}}).then(result => {
                if (result.code == 200) {
                    this.orderList = result.data
                    this.adminForm.ordernum = result.data[0].ordernum;
                    this.adminForm.remark = result.data[0].remark;
                    this.adminForm.name = result.data[0].name;
                    this.adminForm.province = result.data[0].province;
                    // 确保运单号正确初始化
                    this.adminForm.express_code = result.data[0].express_code || '';
                    this.adminForm.tel = result.data[0].tel;
                    this.adminForm.name = result.data[0].name;
                    this.adminForm.city = result.data[0].city;
                    this.adminForm.district = result.data[0].district;
                    this.adminForm.address = result.data[0].address;
                    this.adminForm.num = row.num;
                    this.adminForm.ordernum = row.ordernum;
                    this.adminForm.price = row.price;
                    this.adminForm.f_thumb = row.f_thumb;
                    this.adminForm.title = row.title;
                    this.adminForm.total_price = row.total_price;
                    // 从API响应中获取状态和快递信息
                    this.adminForm.state = result.data[0].state || row.state;
                    this.adminForm.fahuo = result.data[0].fahuo || row.fahuo;
                    this.adminForm.express = result.data[0].express || row.express;
                    // 新增：假设行数据中有 id 字段，将其存储到 adminForm 中，以便后续传递给后端接口
                    this.adminForm.id = row.id;
                    this.editDialogVisible = true;
                    // 等待 DOM 更新后设置表单验证状态
                    this.$nextTick(() => {
                        this.$refs.adminForm && this.$refs.adminForm.clearValidate();
                    });
                } else {
                    this.$message.error(result.msg || '获取详情失败');
                }
            }).catch(error => {
                this.$message.error('获取详情失败');
            });
        },
        toSearch() {
            const formatDate = (date) => {
                if (!date) return '';
                const d = new Date(date);
                const year = d.getFullYear();
                const month = String(d.getMonth() + 1).padStart(2, '0');
                const day = String(d.getDate()).padStart(2, '0');
                const hours = String(d.getHours()).padStart(2, '0');
                const minutes = String(d.getMinutes()).padStart(2, '0');
                const seconds = String(d.getSeconds()).padStart(2, '0');
                const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                const timestamp = new Date(formattedDate).getTime();
                return Math.floor(timestamp / 1000); // 转换为秒级时间戳
            };

            this.searchParams = {
                ...this.form,
                start_time: formatDate(this.form.start_time),
                end_time: formatDate(this.form.end_time)
            };
            // Remove empty string properties from searchParams before sending
            Object.keys(this.searchParams).forEach(key => {
                if (this.searchParams[key] === '') {
                    delete this.searchParams[key];
                }
            });
            this.currentPage = 1;
            this.fetchAdminList(this.searchParams);
            // this.changeBgc()
        },
        changeBgc(){
            this.$http.get('/admin/SearchLog/lists', {params: { item: 'order' }}).then(result => {
                if (result.code === 200) {
                    let ids = [];
                    if (Array.isArray(result.data)) {
                        result.data.forEach(item => {
                            if (typeof item === 'string') {
                                ids = ids.concat(item.split(',').map(id => id.trim()));
                            }
                        });
                    }
                    this.highlightOrderIds = ids;
                } else {
                    this.$message.error(result.msg);
                    this.adminList = [];
                    this.total = 0;
                }
            })
        },
        reset() {
            this.form = {
                search: "",
                type: "",
                pay_type: "",
                channel_id:"",
                state: "",
                fahuo: "",
                start_time: "",
                end_time: ""
            };
            this.searchParams = {};
            this.currentPage = 1;
            this.fetchAdminList();
            this.changeBgc()
        },
        submitForm() {
            // 如果订单已经发货（state === 2），不允许改为不发货
            if (this.adminForm.state === 1 && this.adminForm.fahuo === 2) {
                this.$message.error('订单已发货，不能改为不发货');
                return;
            }

            // 如果选择不发货，直接提交
            if (this.adminForm.state === 1) {
                const formData = {
                    ...this.adminForm,
                    province: this.adminForm.province,
                    tel: this.adminForm.tel,
                    name: this.adminForm.name,
                    city: this.adminForm.city,
                    district: this.adminForm.district,
                    address: this.adminForm.address,
                    express_code: this.adminForm.express_code === undefined ? '' : this.adminForm.express_code
                };

                // 提交表单
                this.$http.post('/admin/Order/orderSend', formData).then(result => {
                    if (result.code === 200) {
                        this.$message.success(result.msg);
                        this.addDialogVisible = false;
                        this.editDialogVisible = false;
                        this.fetchAdminList();
                    } else {
                        this.$message.error(result.msg);
                    }
                });
                return;
            }

            // 如果选择发货，验证快递公司和运单号
            if (this.adminForm.state === 2) {
                // 验证快递公司
                if (!this.adminForm.express) {
                    this.$message.error('请选择快递公司');
                    return;
                }

                /* // 如果不是自提，验证运单号
                 if (this.adminForm.express !== 9 && !this.adminForm.express_code) {
                     this.$message.error('请填写运单号');
                     return;
                 }*/
            }

            const formData = {
                ...this.adminForm,
                province: this.adminForm.province,
                tel: this.adminForm.tel,
                name: this.adminForm.name,
                city: this.adminForm.city,
                district: this.adminForm.district,
                address: this.adminForm.address,
                express_code: this.adminForm.express_code === undefined ? '' : this.adminForm.express_code
            };

            // 提交表单
            this.$http.post('/admin/Order/orderSend', formData).then(result => {
                if (result.code === 200) {
                    this.$message.success(result.msg);
                    this.addDialogVisible = false;
                    this.editDialogVisible = false;
                    this.fetchAdminList();
                } else {
                    this.$message.error(result.msg);
                }
            });
        },
        ToDaoChu(){
            this.showDaoChuDialog = true;
        },

        exportToExcel() {
            // 从本地存储中获取 userInfo
            const userInfo = JSON.parse(localStorage.getItem('userInfo'));
            if (!userInfo || !userInfo.token) {
                // 如果 token 不存在，给出提示
                this.$message.error('token 不存在，请重新登录');
                return;
            }
            const token = userInfo.token;
            // 拼接搜索条件参数
            let queryParams = `token=${token}`;
            const {search, type, pay_type, state, start_time, end_time, channel_id} = this.form;
            if (search) {
                queryParams += `&search=${encodeURIComponent(search)}`;
            }
            if (type) {
                queryParams += `&type=${type}`;
            }
            if (pay_type) {
                queryParams += `&pay_type=${pay_type}`;
            }
            if (state !== undefined && state !== null && state !== '') {
                queryParams += `&state=${state}`;
            }
            if (channel_id) {
                queryParams += `&channel_id=${channel_id}`;
            }
            const formatDateForExport = (date) => {
                if (!date) return '';
                const d = new Date(date);
                const timestamp = Math.floor(d.getTime() / 1000);
                return timestamp;
            };

            const formattedStartTime = formatDateForExport(start_time);
            const formattedEndTime = formatDateForExport(end_time);

            if (formattedStartTime) {
                queryParams += `&start_time=${formattedStartTime}`;
            }
            if (formattedEndTime) {
                queryParams += `&end_time=${formattedEndTime}`;
            }
            // 构造完整的 URL
            const url = this.$appConfig.baseUrl + `admin/Order/orderExport?${queryParams}`;
            // 在新窗口中打开页面
            window.open(url, '_blank');
        },
        tableRowClassName({ row }) {
            if (this.highlightOrderIds.includes(String(row.id))) {
                return 'highlight-row';
            }
            return '';
        },
        handleRowDblClick(row) {
            // 只有高亮的行才允许移除
            if (!this.highlightOrderIds.includes(String(row.id))) {
                return;
            }
            this.$http.post('/admin/SearchLog/delContent', {
                id: row.id,
                item: 'order'
            }).then(res => {
                if (res.code === 200) {
                    this.$message.success('移除高亮');
                    this.changeBgc(); // 刷新高亮
                } else {
                    this.$message.error(res.msg || '删除失败');
                }
            }).catch(() => {
                this.$message.error('网络错误');
            });
        },
        onQuadClick(row) {
            if (!this._quadClickCount) this._quadClickCount = 0;
            this._quadClickCount++;
            if (this._quadClickTimer) clearTimeout(this._quadClickTimer);
            if (this._quadClickCount === 4) {
                this.handleRowDblClick(row);
                this._quadClickCount = 0;
                this._quadClickTimer = null;
            } else {
                this._quadClickTimer = setTimeout(() => {
                    this._quadClickCount = 0;
                    this._quadClickTimer = null;
                }, 2000);
            }
        }
    },
    watch: {
        'adminForm.state': function (newVal) {
            // 当状态改变时，清除验证
            this.$nextTick(() => {
                this.$refs.adminForm && this.$refs.adminForm.clearValidate();
            });
        },
        'adminForm.express': function (newVal) {
            // 当快递公司改变时，清除验证
            this.$nextTick(() => {
                this.$refs.adminForm && this.$refs.adminForm.clearValidate();
            });
        }
    }
};
</script>
<style lang="less" scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}

/deep/ .el-dialog__header {
    padding: 10px !important;
    text-align: center;
}

.admin-page {
    padding: 24px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);

    .page-header {
        margin-bottom: 8px;
        padding-bottom: 8px;

        .header-title {
            font-size: 20px;
            font-weight: 600;
            color: #1f2937;
            line-height: 1.4;
        }
    }

    .el-table {
        margin-top: 12px;
        border-radius: 8px;
        overflow: hidden;

        :deep(th) {
            background-color: #f9fafb !important;
            font-weight: 500;
            color: #4b5563;
        }

        :deep(td) {
            padding: 12px 0;
        }

        .delete-btn {
            color: #dc2626;
            transition: all 0.3s;

            &:hover {
                color: #ef4444;
            }
        }
    }

    .el-pagination {
        margin-top: 24px;
        padding: 12px 0;
        text-align: right;

        :deep(.el-pagination__total) {
            margin-right: 12px;
        }

        :deep(.btn-prev),
        :deep(.btn-next) {
            border-radius: 4px;
            background-color: #fff;
        }

        :deep(.el-pager li) {
            border-radius: 4px;
            background-color: #fff;

            &.active {
                background-color: #2563eb;
            }
        }
    }

    .el-dialog {
        border-radius: 12px;
        overflow: hidden;
        max-height: 90vh;
        display: flex;
        flex-direction: column;

        :deep(.el-dialog__header) {
            padding: 20px 24px !important;
            border-bottom: 1px solid #f0f2f5;
            margin: 0;

            .el-dialog__title {
                font-size: 18px;
                font-weight: 600;
                color: #1f2937;
            }
        }

        :deep(.el-dialog__body) {
            padding: 32px 24px;
            flex: 1;
            overflow-y: auto;

            .el-form-item {
                .el-input,
                .el-select {
                    width: 320px;
                }
            }
        }

        :deep(.el-tree) {
            max-height: 300px;
            overflow-y: auto;
            border: 1px solid #DCDFE6;
            border-radius: 4px;
            padding: 10px;
        }

        :deep(.el-dialog__footer) {
            padding: 16px 24px;
            border-top: 1px solid #f0f2f5;
        }

        :deep(.el-form-item__label) {
            font-weight: 500;
            color: #374151;
        }

        :deep(.el-button) {
            padding: 8px 20px;
            transition: all 0.3s;

            &:hover {
                transform: translateY(-1px);
            }
        }
    }
}

.tip-text {
    font-size: 12px;
    color: #999;
    margin-top: 5px;
    display: block;
}

/deep/ .el-tab-pane {
    height: 650px;
    overflow-y: auto;
}

.search-item {
    margin-right: 10px;
}

.search-label {
    margin-right: 5px;
    white-space: nowrap;
    font-size: 14px;
    color: #606266;
    //min-width: 60px;
    text-align: right;
}

/deep/ .el-radio {
    padding: 0 10px !important;
}

.excel-uploader {
    display: block;
}

.uploader-box {
    width: 200px;
    height: 80px;
    border: 1px dashed #d9d9d9;
    border-radius: 4px;
    text-align: center;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    transition: border-color 0.3s;
}

.uploader-box:hover {
    border-color: #409EFF;
}

.uploader-box i {
    font-size: 28px;
    color: #8c8c8c;
    margin-bottom: 4px;
}

.uploader-box span {
    color: #8c8c8c;
    font-size: 14px;
}

.uploaded-file {
    width: 200px;
    height: 80px;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    padding: 10px 15px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #fafafa;
}

.uploaded-file i {
    font-size: 24px;
    color: #409EFF;
    margin-right: 10px;
}

.uploaded-file span {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.upload-tip {
    margin-top: 8px;
    font-size: 12px;
    color: #999;
    display: flex;
    align-items: center;
}

.upload-tip i {
    margin-right: 4px;
}

.import-result {
    padding: 10px 0;
}

.stats-card {
    display: flex;
    margin-bottom: 20px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    overflow: hidden;
}

.stat-item {
    flex: 1;
    text-align: center;
    padding: 15px 0;
    border-right: 1px solid #ebeef5;
}

.stat-item:last-child {
    border-right: none;
}

.stat-title {
    font-size: 14px;
    color: #909399;
    margin-bottom: 8px;
}

.stat-value {
    font-size: 22px;
    font-weight: bold;
    color: #606266;
}

.stat-value.error {
    color: #f56c6c;
}

/deep/ .el-dialog{
    margin-top: 2vh !important;
}

.red-input-no-border {
    margin-left: 10px;
    color: red !important;
    font-size: 20px;
    width: 160px;
    background-color: transparent;
    cursor: default;
}

/deep/ .highlight-row {
    background-color: #fffbe6 !important;
}

</style>


